package com.shaoyu.tools.event.config;


import com.shaoyu.tools.event.core.CustomSubscribeExceptionHandler;
import com.shaoyu.tools.event.core.EventBusExecutor;
import com.shaoyu.tools.event.core.ConcurrentWrap;
import com.shaoyu.tools.event.core.SubscriberExceptionHandlerDispatcher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Desc :
 * @Author: shaoyu
 * @Date : 2022/11/1 10:53
 */
public class EventBusConfig {

    public EventBusConfig(){
        System.out.println("EventBusConfig");
    }

    @Bean
    @ConditionalOnMissingBean(ConcurrentWrap.class)
    public ConcurrentWrap runnableWrap(){
        return new ConcurrentWrap(){};
    }

    @Bean
    @Primary
    public ExecutorService eventButExecutorService(ConcurrentWrap wrap) {
        int cpu = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cpu * 2,
                cpu * 8,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                r -> new Thread(wrap.warp(r),"EventBus"));
        return threadPoolExecutor;
    }

    @Bean
    public EventBusExecutor.EventBusApplicationListener eventBusApplicationListener() {
        return new EventBusExecutor.EventBusApplicationListener();
    }

//    @Bean
//    public AsyncFilterEventBus asyncFilterEventBus(ExecutorService eventButExecutorService,
//                                                   SubscriberExceptionHandlerDispatcher subscriberExceptionHandler){
//        return new AsyncFilterEventBus(eventButExecutorService,subscriberExceptionHandler);
//    }

    @Bean
    public SubscriberExceptionHandlerDispatcher subscriberExceptionHandler(List<CustomSubscribeExceptionHandler> customSubscribeExceptionHandlers){
        return new SubscriberExceptionHandlerDispatcher(customSubscribeExceptionHandlers);
    }
}
